const crypto = require('crypto')
class oauthToken {
  constructor (options) {
    this.options = options || { secret: 'secret', expires_in: 3600 }
  }
  getDigest (buf) {
    return crypto
      .createHmac('md5', this.options.secret)
      .update(buf)
      .digest()
  }
  aesEncrypt (data, key) {
    const cipher = crypto.createCipher('aes192', key)
    var crypted = cipher.update(data, 'utf8', 'base64')
    crypted += cipher.final('base64')
    return crypted
  }

  aesDecrypt (encrypted, key) {
    const decipher = crypto.createDecipher('aes192', key)
    var decrypted = decipher.update(encrypted, 'base64', 'utf8')
    decrypted += decipher.final('utf8')
    return decrypted
  }
  checkDigest (buf, digest) {
    var hmac = this.getDigest(buf)
    console.log(digest.compare(hmac))
    if (digest.compare(hmac) !== 0) {
      throw new Error('Error validating token: Invalid token signature.')
    }
  }
  create (data) {
    const { secret, expires_in } = this.options // eslint-disable-line
    data.timestamp = (Date.now() / 1000) | 0
    data.secret = secret
    let accessToken = this.aesEncrypt(JSON.stringify(Object.assign(data, {type: 'access'})), '123')
    accessToken = accessToken.replace(/\+/g, '-').replace(/\//g, '_')
    let refreshToken = this.aesEncrypt(JSON.stringify(Object.assign(data, {type: 'refresh'})), '123')
    refreshToken = refreshToken.replace(/\+/g, '-').replace(/\//g, '_')

    return {
      access_token: accessToken,
      timestamp: data.timestamp,
      expires_in,
      refresh_token: refreshToken
    }
  }
  decode (token) {
    let accessToken = token.access_token.replace(/\-/g, '+').replace(/\_/g, '/') // eslint-disable-line
    return this.aesDecrypt(accessToken, '123')
  }
  refresh (refreshToken) {
    let data = this.decode(refreshToken)
    return this.create(JSON.parse(data))
  }
  isExpired (token) {
    if (token.expires_in === 0) {
      return false
    }
    return ((Date.now() / 1000) | 0) > token.timestamp + token.expires_in
  }
}
module.exports = oauthToken
